package org.yunfeng.manage.http.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.annotation.Resource;
import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.yunfeng.manage.common.result.PicUploadResult;
import org.yunfeng.manage.http.oss.ImageDetails;
import org.yunfeng.manage.http.oss.OssClient;

@RestController
public class FileUploadContraller {
	
	@Resource
	private OssClient ossClient;
	
	private final static Logger logger = LoggerFactory.getLogger(FileUploadContraller.class);
	
	private final static String PICTRUE_SUFFIX = ".*(jpg|png)$";
	
	private final static int ERROR = 1;
	
	private final static int OK = 0;
	
	/**
	 * 图片上传接口: PicUploadResult对象,封装4个插件需求参数:hight,width,error,url	
	 */
	@PostMapping("/pic/upload")
	public PicUploadResult picUpload(MultipartFile uploadFile) throws IllegalStateException, IOException {
		PicUploadResult result = new PicUploadResult();
		int errorCode = OK;
		//判断文件类型
		String fileName = uploadFile.getOriginalFilename();
		if(!isPictureFile(fileName)){
			errorCode = ERROR;
		}
		//判断是否病毒
		if(getFileDetails(uploadFile).isVirus()) {
			errorCode = ERROR;
		}
		//正常
		if(errorCode == OK) {
			result.setHeight(getFileDetails(uploadFile).getHeight());
			result.setWidth(getFileDetails(uploadFile).getWidth());
			//保存文件
			String url = ossClient.saveFile(uploadFile);
			logger.info("url :::> "  + url);
			result.setUrl(url);
		}
		result.setError(errorCode);
		return result;
	}
	
	/** 根据后缀名判断是否图片文件*/
	private boolean isPictureFile(String fileName) {
		return fileName.matches(PICTRUE_SUFFIX) ? true : false;
	}
	
	/** 读取图片宽高, 并检查是否病毒*/
	private ImageDetails getFileDetails(MultipartFile uploadFile) throws IOException {
		BufferedImage image = ImageIO.read(uploadFile.getInputStream());
		ImageDetails details = new ImageDetails();
		try {
			details.setHeight(image.getHeight() + "");
			details.setWidth(image.getWidth() + "");
		} catch (Exception e) {
			logger.error("上传的图片可能是病毒:　", e);
			details.setVirus(true);
		}
		return details;
	}
}
